import { HttpException, Injectable } from '@nestjs/common'
import { CreateCommentDto } from './dto/create-comment.dto'
import { CommentEntity } from './entities/comment.entity'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { JwtService } from '@nestjs/jwt'
import { ListCommentDto } from './dto/list-comment.dto'
import { UserEntity } from '../user/entities/user.entity'

@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(CommentEntity)
    private readonly commentRepository: Repository<CommentEntity>,
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
    private readonly jwtService: JwtService
  ) { }

  // 评论列表
  async list(data: ListCommentDto) {
    const { page, pageSize } = data

    const qb = await this.commentRepository.createQueryBuilder('comment')
    qb.leftJoinAndSelect('comment.user', 'user')
    qb.select(['comment.id', 'comment.name', 'comment.user_id', 'comment.create_time', 'user.nickname', 'user.avatar'])
    qb.orderBy('comment.create_time', 'DESC')
    qb.andWhere('comment.is_del = :is_del', { is_del: 0 })

    if (data.user_id) {
      qb.andWhere('comment.user_id = :user_id', { user_id: data.user_id })
    }

    if (!page && !pageSize) {
      const entries = (await qb.getMany()).map(({ is_del, ...rest }) => rest)
      return {
        entries,
        total: entries.length
      }
    }
    const pageNum = Math.max(1, Number(page) || 1)
    const pageSizeNum = Math.min(100, Math.max(1, Number(pageSize) || 10))
    const total = await qb.getCount()
    const temp = (await qb.skip((pageNum - 1) * pageSizeNum).take(pageSizeNum).getMany()).map(({ is_del, ...rest }) => rest)

    return {
      entries: temp,
      total
    }
  }

  // 添加评论
  async create(data: CreateCommentDto & { user_id: number }) {
    const userExist = await this.userRepository.exists({ where: { id: data.user_id } })
    if (!userExist) {
      throw new HttpException(`该用户不存在`, 404)
    }
    const exist = await this.commentRepository.findOne({
      where: { name: data.name }
    })
    if (exist) throw new HttpException("该留言已存在", 409)

    await this.commentRepository.save({
      name: data.name,
      user_id: data.user_id,
      create_time: Math.floor(Date.now() / 1000)
    })

    return {
      isAdd: true
    }
  }
}
